package example.segment;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Demo {
    int a = 0;
    int b = 0;
    int c = 0;
    final Object a_lock = new Object();
    final Object b_lock = new Object();
    final Object c_lock = new Object();

    public void aAdd() {
        synchronized (a_lock) {
            ++a;
        }
    }

    public void bAdd() {
        synchronized (b_lock) {
            ++b;
        }
    }

    public void aAdd2()  {
        synchronized (a_lock) {
            synchronized (b_lock) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                b++;
            }
            ++a;
        }
    }

    public void bAdd2()   {
        synchronized (b_lock) {
            synchronized (a_lock) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a++;
            }
            ++b;
        }
    }


    public void cAdd() {
        synchronized (c_lock) {
            ++c;

        }
    }

    public static void main(String[] args) throws Exception {
        Demo demo = new Demo();
//        int count = 500;
//        CountDownLatch latch = new CountDownLatch(count);
//        CountDownLatch main = new CountDownLatch(count);
//        for (int i = 0; i < count; i++) {
//            new Thread(() -> {
//                try {
//                    latch.await();
//                } catch (InterruptedException e) {
//                }
//                for (int j = 0; j < 20; j++) {
//                    demo.aAdd();
//                }
//                main.countDown();
//            }).start();
//            latch.countDown();
//        }
//        main.await();
//        System.out.println(demo.a);

        new Thread(demo::aAdd2).start();
        new Thread(demo::bAdd2).start();
    }
}
